package pf

import (
	"chess_platform/controllers"
	"chess_platform/internal/alisdk"
	. "chess_platform/internal/common"
	"chess_platform/internal/token"
	"chess_platform/models/partner"
	"chess_platform/models/pb"
	"fmt"
	"time"
)

//[h5]代理开通流程
type AgentController struct {
	GrantController
}

func (b *AgentController) Prepare() {
	LogPF.Debug("用户输入:" + string(b.Ctx.Input.RequestBody))
	LogPF.Debug("用户访问url:" + b.Ctx.Input.URL())
	b.Res = new(controllers.Response)
	var t controllers.Token
	err := b.Unmarshal(&t)
	if err != nil {
		b.DecodeParamsError(err)
		return
	}
	ex, err := token.Parse(t.Token)
	if err != nil || ex.GetTokenType() != TokenPF {
		LogPF.Error("token解析:" + err.Error())
		b.Res.Code = ErrUserUnauthorized
		b.Res.Msg = MsgErrUserUnauthorized
		b.Response()
		return
	}
	if ex.IsExpire() {
		b.Res.Code = ErrUserUnauthorized
		b.Res.Msg = MsgErrUserExpire
		b.Response()
		return
	}
	b.Uid = ex.GetId()

	keyAccessLimit := fmt.Sprintf("PFUserLimit-%v", b.Uid)
	if !AccessLimit(keyAccessLimit, Al.Frequency, Al.ExpireTime) {
		b.ResponseFail("操作过于频繁，请稍候再操作")
		return
	}

	b.Level = ex.GetLevel()
	status, _ := ex.GetInfo().(float64)

	b.Status = int64(status)
	if b.Status == PfFirstTopUpSuccess {
		b.Res.Code = ErrUserUnauthorized
		b.Res.Msg = MsgUserNotPass
		b.Response()
		return
	}
	field := []string{"status", "pid", "create_time"}
	u, err := partner.SpecifyUserInfoById(b.Uid, field)
	if err != nil {
		LogPF.Error(b.DatabaseError(err.Error()))
		return
	}
	if u == nil {
		b.Res.Code = ErrNotFound
		b.Res.Msg = MsgErrUserNotFound
		b.Response()
		return
	}

	b.Status = u.Status
	LogPF.Debug(fmt.Sprintf("用户访问(ID:%v,Level:%v,Status:%v)url:%v", b.Uid, b.Level, b.Status, b.Ctx.Input.URL()))

	//如果代理仅仅是注册成功了或审核为拒绝，但是一直没输入授权码，那么就更新注册时间为现在,当作没有超过24小时
	//判断此次申请是否已经超过24小时，一级代理都没有处理,就自动变成拒绝
	//拒绝之后,要修改用户状态,并且要还一个名额给一级代理
	if b.Ctx.Input.URL() == "/v1/partner/user/self-info" {
		return
	}
	ok, err := partner.HandleAgentStatus(u.CreateTime, b.Uid, u.Pid, u.GroupId,
		u.Status == RegisterSuccess || u.Status == VerifyNotPass)

	if err != nil {
		LogPF.Error(b.DatabaseError(err.Error()))
		return
	}
	if !ok {
		b.ResponseFail("您的申请长时间未充值激活,自动拒绝")
		return
	}

}

func (b *AgentController) URLMapping() {
	b.Mapping("TopUp", b.TopUp)
	b.Mapping("InitialBuyCard", b.InitialBuyCard)
	b.Mapping("BindPhone", b.BindPhone)
	b.Mapping("SelfInfo", b.SelfInfo)
	b.Mapping("AgentInfo", b.AgentInfo)

}

// @Title 第一次充值(显示价格)
// @Description 第一次充值(显示价格)
// @Success 0
// @router /top-up [post]
func (b *AgentController) TopUp() {
	if b.Status != PfVerifyPass {
		b.Res.Code = ErrUserUnauthorized
		b.Res.Msg = MsgErrUserForbidden
		b.Response()
		return
	}
	//根据b.Level来获取应该充值哪一个
	/*
		总代(一级代理)与二级代理及二级代理以下的代理第一次充值价格可能不一样
	*/
	if b.Level == Level1 {
		tu, err := partner.TopUpByLevel(TopUpLevel11)
		if err != nil {
			LogPF.Error(b.DatabaseError(err.Error()))
			return
		}
		b.Res.Data = tu
	} else {
		tu, err := partner.TopUpByLevel(TopUpLevel12)
		if err != nil {
			LogPF.Error(b.DatabaseError(err.Error()))
			return
		}
		b.Res.Data = tu
	}

	b.ResponseSuccess()
}

// @Title 第一次充值(爱贝支付)
// @Description 第一次充值(爱贝支付)
// @Param   pay_type       body    int true      "支付类型,2-微信支付,3-支付宝支付"
// @Param   url_r          body    int true      "支付成功回调url"
// @Param   url_h          body    int true      "支付取消回调url"
// @Success 0
// @router /initial-buy-card [post]
func (b *AgentController) InitialBuyCard() {
	if b.Status != PfVerifyPass {
		b.Res.Code = ErrUserUnauthorized
		b.Res.Msg = MsgErrUserForbidden
		b.Response()
		return
	}
	type Params struct {
		PayType int64  `json:"pay_type" valid:"Range(2,3)"`
		UrlR    string `json:"url_r" valid:"Required"`
		UrlH    string `json:"url_h" valid:"Required"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}

	//根据b.Level来获取应该充值哪一个
	/*
		总代(一级代理)与二级代理及二级代理以下的代理第一次充值价格可能不一样
	*/
	var level int64
	if b.Level == Level1 {
		level = TopUpLevel11
	} else {
		level = TopUpLevel12
	}
	tu, err := partner.TopUpByLevel(level)
	if err != nil {
		LogPF.Error(b.DatabaseError(err.Error()))
		return
	}
	order := map[string]interface{}{
		"uid":        b.Uid, //代理id
		"pay_type":   p.PayType,
		"order_type": OrderDiamond,
		"amount":     tu.Amount,
		"card_num":   tu.CardNum,
		"status":     OrderNotPay,
		"is_first":   FirstTimeBuyCard,
		"order_time": time.Now().Unix(),
	}
	orderId, err := partner.PreOrderPay(order)
	if err != nil {
		LogPF.Error(b.DatabaseError(err.Error()))
		return
	}
	notifyUrl := BasePayCallBack + "/v1/pf/ipay-callback"
	orderIdStr := fmt.Sprintf("%v%v", PfIPayPre, orderId)
	price := float32(tu.Amount) / 100 //我们数据库存在的整型,单位是分,所以要除以100转为元
	transId, err := H5IPay.CreateIpayOrder(1, "", orderIdStr, price, "xiashen", "", notifyUrl)
	if err != nil {
		LogPF.Error(b.SystemError(err.Error()))
		return
	}
	updateData := map[string]interface{}{
		"transaction_id": transId,
	}
	_, err = partner.UpdateOrder(updateData, orderId)
	if err != nil {
		LogPF.Error(fmt.Sprintf("写入爱贝的订单号失败:%v", err.Error()))
	}
	payUrl, err := H5IPay.GetHtml5PayUrl(transId, p.UrlR, p.UrlH, IPayPayType(p.PayType))
	if err != nil {
		LogPF.Error(b.SystemError(err.Error()))
		return
	}
	b.Res.Data = payUrl
	b.ResponseSuccess()
}

// @Title 绑定手机号
// @Description 绑定手机号
// @Param   phone     body    string  true      "手机号"
// @Param   password  body    string  true      "密码"
// @Param   captcha   body    string  true      "短信验证码"
// @Success 0 {string} 状态码
// @Failure 399
// @router /bind-phone [post]
func (b *AgentController) BindPhone() {
	if b.Status != PfRegisterSuccess {
		b.Res.Code = ErrUserUnauthorized
		b.Res.Msg = MsgErrUserForbidden
		b.Response()
		return
	}

	type Params struct {
		Phone    string
		Password string
		Captcha  string
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}

	b.Valid.Required(p.Phone, "phone").Message("手机号不能为空")
	b.Valid.Phone(p.Phone, "phone").Message("错误的手机号")
	b.Valid.MinSize(p.Password, 6, "password").Message("密码长度为6-15个字符")
	b.Valid.MaxSize(p.Password, 15, "password").Message("密码长度为6-15个字符")
	b.Valid.Required(p.Captcha, "captcha").Message("验证码不能为空")
	b.Valid.Numeric(p.Captcha, "captcha").Message("验证码为6位数字")
	b.Valid.Length(p.Captcha, 6, "captcha").Message("验证码为6位数字")
	if !b.VerifyParamsError() {
		return
	}
	err, ok := alisdk.VerifySMSCaptcha(p.Phone, p.Captcha, KeyPfPhone, MemCache)
	if !ok {
		b.Res.Code = ErrCaptchaVerify
		b.Res.Msg = err.Error()
		b.Response()
		LogPF.Notice(err.Error())
		return
	}

	uid, err := partner.IsUserExistByPhone(p.Phone)
	if err != nil {
		LogPF.Error(b.DatabaseError(err.Error()))
		return
	}
	if uid != 0 {
		b.Res.Code = ErrAlreadyExist
		b.Res.Msg = MsgErrPhoneAlreadyExist
		b.Response()
		return
	}
	status := PfBindPhoneSuccess
	user := map[string]interface{}{
		"phone":       p.Phone,
		"password":    Md5sum(p.Password),
		"status":      status,
		"create_time": time.Now().Unix(),
	}

	_, err = partner.UpdateUser(user, b.Uid)
	if err != nil {
		LogPF.Error(b.DatabaseError(err.Error()))
		return
	}
	b.Res.Data = map[string]interface{}{
		"status": status,
		"level":  b.Level,
	}
	b.ResponseSuccess()
}

// @Title 获取自己用户信息,在代理未成功正式代理时使用
// @Description 获取自己用户信息,在代理未成功正式代理时使用
// @Success 0 {object} partner.User
// @router /self-info [post]
func (b *AgentController) SelfInfo() {
	field := []string{"uid", "nickname", "head_img_url", "status", "level"}
	dbUser, err := partner.SpecifyUserInfoById(b.Uid, field)
	if err != nil {
		LogPF.Error(b.DatabaseError(err.Error()))
		return
	}
	if dbUser == nil {
		b.Res.Code = ErrNotFound
		b.Res.Msg = MsgErrUserNotFound
		b.Response()
		return
	}
	data := map[string]interface{}{
		"uid":          dbUser.Uid,
		"nickname":     dbUser.Nickname,
		"head_img_url": dbUser.HeadImgUrl,
		"status":       dbUser.Status,
		"level":        dbUser.Level,
	}
	b.Res.Data = data
	b.ResponseSuccess()
}

// @Title 获取上级代理用户信息
// @Description 获取上级代理用户信息
// @Success 0 {object} partner.User
// @Failure 399
// @router /agent-info [post]
func (b *AgentController) AgentInfo() {
	field := []string{"pid", "group_id", "create_time"}
	u, err := partner.SpecifyUserInfoById(b.Uid, field)
	if err != nil {
		LogPF.Error(b.DatabaseError(err.Error()))
		return
	}
	if u == nil {
		b.Res.Code = ErrNotFound
		b.Res.Msg = MsgErrUserNotFound
		b.Response()
		return
	}
	//上级是合伙人
	if u.Pid == 0 && u.GroupId != 0 {
		pbUser, err := pb.UserInfoById(u.GroupId)
		if err != nil {
			LogPF.Error(b.DatabaseError(err.Error()))
			return
		}
		if pbUser.Uid == 0 {
			b.Res.Code = ErrNotFound
			b.Res.Msg = MsgErrUserNotFound
			b.Response()
			return
		}
		data := map[string]interface{}{
			"nickname":     pbUser.RealName,
			"head_img_url": "", //合伙人暂时没有头像
			"phone":        pbUser.Phone,
			"level":        0, //合伙人级别为0,总代(一级代理)为1
		}

		b.Res.Data = data
		b.ResponseSuccess()

	} else if u.Pid != 0 {
		field = []string{"nickname", "head_img_url", "phone", "level"}
		u, err := partner.SpecifyUserInfoById(u.Pid, field)
		if err != nil {
			LogPF.Error(b.DatabaseError(err.Error()))
			return
		}
		if u == nil {
			b.Res.Code = ErrNotFound
			b.Res.Msg = MsgErrUserNotFound
			b.Response()
			return
		}

		data := map[string]interface{}{
			"nickname":     u.Nickname,
			"head_img_url": u.HeadImgUrl,
			"phone":        u.Phone,
			"level":        u.Level,
		}

		b.Res.Data = data
		b.ResponseSuccess()
	} else {
		b.ResponseFail("注册异常,找不到上级代理信息,请联系客服")
		return
	}
}
